﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xiaov.SmartWeb.Model.ActiveRecord;
using Xiaov.SmartWeb.Infrastructure.ExtMethod;
using Xiaov.SmartWeb.Infrastructure.Common;
using Xiaov.SmartWeb.Model.Domain;

namespace Xiaov.SmartWeb.Model
{
    public  class BasePage:System.Web.UI.Page
    {
        /// <summary>
        /// 用户
        /// </summary>
        public S_PM_USER PUser { get; set; }

        /// <summary>
        /// 模块
        /// </summary>
        public S_PM_MODULE PModule { get; set; }

        /// <summary>
        /// 用户屏幕高度
        /// </summary>
        public int UserScreenHeight { get; set; }

        /// <summary>
        /// 页面路径
        /// </summary>
        public string PModuleUrl { get { return Request.Url.AbsolutePath; } }

        /// <summary>
        /// 权限集合
        /// </summary>
        public List<Permission> Permissions { get; set; }

        protected override void OnInit(EventArgs e)
        {            
            GetUser();             
            base.OnInit(e);
        }

        /// <summary>
        /// 获取当前用户
        /// </summary>
        public void GetUser()
        {
            if (PUser == null)
            {
                if (Page.User.Identity.IsAuthenticated)
                {
                    PUser = S_PM_USER.TryFind(Page.User.Identity.Name);
                    if (PUser == null)
                    {
                        General.ShowAlert("错误提示", "数据库中没有这个用户[" + Page.User.Identity.Name + "]", "/Login.aspx");
                    }
                }
                else
                    General.ShowAlert("错误提示", "没有登录", "/Login.aspx");
            }
            
        }

        /// <summary>
        /// 权限横切，根据请求路径(严格检查)判断权限
        /// </summary>
        public void PM_Filter()
        {
            PM_FilterByProperty(ModulePropoty.MODULEURL, Request.RawUrl);
        }
        
        /// <summary>
        /// 统计系统权限横切，检查Tn参数及值，忽略其他参数检查
        /// </summary>
        public void PM_Filter_Statistical()
        {
            if (Request.Params["tn"].ToRequestString() != "")
            {
                //移除参数dwbm year month
                string url = Request.Url.AbsolutePath + "?tn=" + Request.Params["tn"];
                PM_FilterByProperty_Relax(ModulePropoty.MODULEURL, url);
            }
        }

        /// <summary>
        /// 忽略URL参数的URL检查
        /// </summary>
        public void PM_Filter_AbsolutePath()
        {
            PM_FilterByProperty(ModulePropoty.MODULEURL, Request.Url.AbsolutePath);
        }

       
        /// <summary>
        /// (松散)权限切入：根据模块属性值来寻找唯一的模块
        /// </summary>
        /// <param name="property">模块的属性</param>
        /// <param name="value">属性值</param>
        public void PM_FilterByProperty_Relax(ModulePropoty property, object value)
        {
            //获取模块
            PModule = S_PM_MODULE.FindAll(NHibernate.Criterion.Expression.Sql(property.ToString()+" like '"+value+"'")).FirstOrDefault();
            bool Allow = false;//进入权限
            if (PModule != null)
            {
                //超管 也许并不应设定这个东东....先这么写吧
                if (PUser.Super)
                {
                    Allow = true;
                }
                //模块有哪些角色可以访问
                ROLE_MODULE_KEY key = new ROLE_MODULE_KEY();
                key.ModuleID = PModule.MODULEID;
                List<string> list = PModule.RolePermission.Select(s => s.ROLE_MODULE.ROLEID).ToList();
                //用户有哪些角色
                List<string> listr = PUser.UserRoles.Select(s => s.USER_ROLE.ROLEID).ToList();
                //角色并集操作
                List<string> listResult = listr.Intersect(list).ToList();

                if (listResult.Count > 0)
                {
                    Allow = true;
                }

                //取所有用户角色对该模块的设定
                foreach (var r in listResult)
                {
                    Permissions = new List<Permission>();
                    //获取该模块的所有的权限总值 (每个角色对应一个总值)
                    List<int> p = PModule.RolePermission.Where(s => s.ROLE_MODULE.ROLEID == r).Select(s => s.PERMISSION).ToList();
                    //获取该模块有几个权限
                    int length = PModule.ACTIONSTRING.Split(',').Length;
                    //获取每个权限
                    for (int i = 0; i < length; i++)
                    {
                        //
                        Permission pm = new Permission();
                        pm.PKey = (PermissionKey)Enum.Parse(typeof(PermissionKey), i.ToString());
                        pm.Allow = false;
                        foreach (var p0 in p)
                        {
                            int pv = (int)Math.Pow(2, i);
                            if ((p0 & pv) == pv)
                            {
                                pm.Allow = true;
                                break;
                            }
                        }
                        Permissions.Add(pm);
                    }
                }
            }
            if (!Allow)
            {
                Xiaov.SmartWeb.Infrastructure.Common.General.ShowAlert("错误提示", "没有权限", "#");
            }
        }

        /// <summary>
        /// (严格)权限切入：根据模块属性值来寻找唯一的模块
        /// </summary>
        /// <param name="property">模块的属性</param>
        /// <param name="value">属性值</param>
        public void PM_FilterByProperty(ModulePropoty property, object value)
        {
            //获取模块
            PModule = S_PM_MODULE.FindAllByProperty(property.ToString(), value).FirstOrDefault();
            bool Allow = false;//进入权限
            if (PModule != null)
            {
                //超管 也许并不应设定这个东东....先这么写吧
                if (PUser.Super)
                {
                    Allow = true;
                }
                //模块有哪些角色可以访问
                ROLE_MODULE_KEY key = new ROLE_MODULE_KEY();
                key.ModuleID = PModule.MODULEID;
                List<string> list = PModule.RolePermission.Select(s => s.ROLE_MODULE.ROLEID).ToList();
                //用户有哪些角色
                List<string> listr = PUser.UserRoles.Select(s => s.USER_ROLE.ROLEID).ToList();
                //角色并集操作
                List<string> listResult = listr.Intersect(list).ToList();

                if (listResult.Count > 0)
                {
                    Allow = true;
                }

                //取所有用户角色对该模块的设定
                foreach (var r in listResult)
                {
                    Permissions = new List<Permission>();
                    //获取该模块的所有的权限总值 (每个角色对应一个总值)
                    List<int> p = PModule.RolePermission.Where(s => s.ROLE_MODULE.ROLEID == r).Select(s => s.PERMISSION).ToList();
                    //获取该模块有几个权限
                    int length = PModule.ACTIONSTRING.Split(',').Length;
                    //获取每个权限
                    for (int i = 0; i < length; i++)
                    {
                        //
                        Permission pm = new Permission();
                        pm.PKey = (PermissionKey)Enum.Parse(typeof(PermissionKey), i.ToString());
                        pm.Allow = false;
                        foreach (var p0 in p)
                        {
                            int pv = (int)Math.Pow(2, i);
                            if ((p0 & pv)==pv)
                            {
                                pm.Allow = true;
                                break;
                            }
                        }
                        Permissions.Add(pm);
                    }
                }
            }
            if (!Allow)
            {
                Xiaov.SmartWeb.Infrastructure.Common.General.ShowAlert("错误提示","没有权限","#");
            }
        }
    }
}
